package com.example.aigc_education.controller.common;

import com.example.aigc_education.constant.CacheConstants;
import com.example.aigc_education.constant.Constants;
import com.example.aigc_education.utils.Base64;
import com.example.aigc_education.utils.IdUtils;
import com.example.aigc_education.utils.RedisCache;
import com.example.aigc_education.utils.ResultUtil;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class CaptchaController
{

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath; // 生产数学验证码的Producer

    @Resource
    private RedisCache redisCache; // Redis缓存服务


    /**
     * 生成验证码
     * 
     * @param response HttpServletResponse对象，用于设置HTTP响应头信息
     * @return ResultUtil对象，包含验证码信息或错误信息
     * @throws IOException 如果发生I/O错误
     */
    @GetMapping("/captchaImage")
    public ResultUtil getCode(HttpServletResponse response) throws IOException {
        ResultUtil result = ResultUtil.success();

        // 生成验证码前的准备工作
        String uuid = IdUtils.simpleUUID(); // 生成唯一标识符
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid; // 构造验证码在缓存中的键名

        String capStr = null;
        String code = null;
        BufferedImage image = null;

        // 生成数学验证码
        String capText = captchaProducerMath.createText();
        capStr = capText.substring(0, capText.lastIndexOf("@"));
        code = capText.substring(capText.lastIndexOf("@") + 1);
        image = captchaProducerMath.createImage(capStr);
        log.info("验证码{}", code);


        // 将验证码代码存储到Redis缓存中
        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换验证码图像为字节流并进行Base64编码
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return ResultUtil.error(e.getMessage()); // 图像写入失败，返回错误信息
        }

        // 将验证码信息封装到Result中返回
        result.put("code", code);   // 用于测试使用
        result.put("uuid", uuid);
        result.put("img", Base64.encode(os.toByteArray()));
        return result;
    }
}
